(function() {
	var system = require('system');
	var config = {
			JQUERY: 'jquery-1.11.0.min.js',
			ECHARTS: 'echarts-all.js',
			DEFAULT_WIDTH: '800',
			DEFAULT_HEIGHT: '400'
		},
		parseParams, getOption, render, pick, usage;

	usage = function() {
		console.log("\nUsage: phantomjs echarts-convert.js -options options -outfile filename -width width -height height" + "OR" + "Usage: phantomjs echarts-convert.js -infile URL -outfile filename -width width -height height\n");
	};

	pick = function() {
		var args = arguments,
			i, arg, length = args.length;
		for (i = 0; i < length; i += 1) {
			arg = args[i];
			if (arg !== undefined && arg !== null && arg !== 'null' && arg != '0') {
				return arg;
			}
		}
	};


	parseParams = function() {
		var map = {},
			i, key;
		if (system.args.length < 2) {
			usage();
			phantom.exit();
		}
		for (i = 0; i < system.args.length; i += 1) {
			if (system.args[i].charAt(0) === '-') {
				key = system.args[i].substr(1, i.length);
				map[key] = system.args[i + 1];
			}
		}
		return map;
	};

	render = function(params) {
		var page = require('webpage').create(),
			createChart;

		page.onConsoleMessage = function(msg) {
			console.log(msg);
		};

		page.onAlert = function(msg) {
			console.log(msg);
		};

		createChart = function(screenWidth, height) {
			var counter = 0;
			var width;

			function decrementImgCounter() {
				counter -= 1;
				if (counter < 1) {
					console.log(messages.imagesLoaded);
				}
			}

			function loadScript(codeStr) {
				var script = $('<script>').attr('type', 'text/javascript');
				script.html(codeStr);
				document.getElementsByTagName("head")[0].appendChild(script[0]);
			}

			function loadImages() {
				var images = $('image'),
					i, img;
				if (images.length > 0) {
					counter = images.length;
					for (i = 0; i < images.length; i += 1) {
						img = new Image();
						img.onload = img.onerror = decrementImgCounter;
						img.src = images[i].getAttribute('href');
					}
				} else {
					// console.log('The images have been loaded');
				}
			}

			function getOption() {
				var option = $('body').text();
				$('body').text('');
				return option;
			}

			// 获得js
			var inputOption = getOption();
			if (inputOption != 'undefined') {
				// 加载js，并解析出name='options' 的参数
				loadScript(inputOption);
				options.animation = false;
			}

			if (options.chartType == 'line-bar') {
				width = screenWidth * 0.8;
			} else if (options.chartType == 'chart-pie') {
				width = 800;
			}

			// we render the image, so we need set background to white.
			$(document.body).css('backgroundColor', 'white');
			var container = $("<div>").appendTo(document.body);
			container.attr('id', 'container');
			container.css({
				width: width,
				height: height
			});

			// render the chart
			var myChart = echarts.init(container[0], 'macarons');
			myChart.setOption(options);
			// load images
			loadImages();
			return width;
		};

		// parse the params
		page.open(params.url, function(status) {
			// inject the dependency js
			page.injectJs(config.JQUERY);
			page.injectJs(config.ECHARTS);

			// params.width = window.screen.width * 0.8;
			// var width = pick(params.width, config.DEFAULT_WIDTH);
			var height = pick(params.height, config.DEFAULT_HEIGHT);

			// width = 960;
			// create the chart
			var outWidth = page.evaluate(createChart, window.screen.width, height);

			// define the clip-rectangle
			page.clipRect = {
				top: 0,
				left: 0,
				width: outWidth,
				height: height
			};
			// render the image
			page.render(params.outfile);
			// console.log('render complete:' + params.outfile);
			console.log("success");
			// exit
			phantom.exit();
		});
	};
	// get the args
	var params = parseParams();

	// render the image
	try {
		render(params);
	} catch (e) {
		console.log("fail");
		phantom.exit();
	}
}());